#include "OfflineMessageModel.hpp"
#include "db.h"

// 插入离线信息
bool OfflineMessageModel::insert(int userid,std::string js)
{
    char buffer[1024];
    int n = sprintf(buffer,"insert into OfflineMessage values(%d,'%s')"
    , userid, js.c_str());

    assert(n != 0);
    (void)n;

    MySQL sql;
    if(sql.connect())
    {
         if(sql.update(buffer))
         return true;
    }

    return false;
}

void OfflineMessageModel::remove(int userid)
{
    char buffer[1024];

     int n = sprintf(buffer,"delete from OfflineMessage where user_id = %d", userid);

    assert(n != 0);
    (void)n;

    MySQL sql;
    if(sql.connect())
        sql.update(buffer);
}

std::vector<std::string> OfflineMessageModel::query(int userid)
{
    char buffer[1024];
    int n = sprintf(buffer,"select message from OfflineMessage where user_id = %d", userid);

    assert(n != 0);
    (void)n;

    std::vector<std::string> ret;

    MySQL sql;
    if(sql.connect())
    {
        MYSQL_RES* sqlResult = sql.query(buffer);
        if(sqlResult != nullptr)
        {
            MYSQL_ROW row;
            //mysql_fetch_row这个会自动按行读取 
            while( ( row = mysql_fetch_row(sqlResult) )  != nullptr)
            {
                ret.push_back(row[0]);
            }
        }
          mysql_free_result(sqlResult);
    }

    return ret;
}
